package com.s64.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.s64.entity.Book;
import com.s64.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public static final String BOOK_KEY = "s64:books";

    @PostConstruct
    public void prepareList() {
        List<Book> list = super.list(Wrappers.lambdaQuery(Book.class).eq(Book::getSecondsKill, 1));
        Map<String, String> map = new HashMap<>();
        list.forEach(item -> {
            map.put(item.getId().toString(), item.getAmount().toString());
        });
        stringRedisTemplate.opsForHash().putAll(BOOK_KEY, map);
        System.out.println("预热成功");
    }

    @Override
    public void setAmount(Long bookId, int amount) {
        getBaseMapper().updateAmount(bookId, amount);
    }
}
